<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>钉钉配置管理</title>
    <link rel="stylesheet" href="../../component/pear/css/pear.css" />
</head>

<body class="pear-container">
    <!-- 筛选表单区域 -->
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form" action="">
                <div class="layui-form-item">
                    <!-- 配置名称筛选 -->
                    <div class="layui-form-item layui-inline">
                        <label class="layui-form-label">名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="name" id="name" placeholder="输入配置名称" class="layui-input">
                        </div>
                    </div>
                    <!-- 配置名称筛选 -->
                    <div class="layui-form-item layui-inline">
                        <label class="layui-form-label">Token</label>
                        <div class="layui-input-inline">
                            <input type="text" name="access_token" id="access_token" placeholder="输入机器人Token" class="layui-input">
                        </div>
                    </div>
                    <!-- 配置名称筛选 -->
                    <div class="layui-form-item layui-inline">
                        <label class="layui-form-label">加签密钥</label>
                        <div class="layui-input-inline">
                            <input type="text" name="secret" id="secret" placeholder="输入加签密钥" class="layui-input">
                        </div>
                    </div>
                    <!-- 配置状态筛选 -->
                    <div class="layui-form-item layui-inline">
                        <label class="layui-form-label">状态</label>
                        <div class="layui-input-inline">
                            <select name="is_active" id="is_delete" lay-search>
                                <option value="">请下拉选择</option>
                                <option value="0">关闭</option>
                                <option value="1">开启</option>
                            </select>
                        </div>
                    </div>
                    <br>
                    <!-- 搜索/重置按钮 -->
                    <div class="layui-form-item layui-inline">
                        <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="base-query">
                            <i class="layui-icon layui-icon-search"></i>
                            查询
                        </button>
                        <button type="reset" class="pear-btn pear-btn-md">
                            <i class="layui-icon layui-icon-refresh"></i>
                            重置
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- 表格展示区域 -->
    <div class="layui-card">
        <div class="layui-card-body">
            <table id="base-table" lay-filter="base-table"></table>
        </div>
    </div>

    <!-- 表格工具栏（新增按钮） -->
    <script type="text/html" id="base-toolbar">
		<button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add_dingtalk">
	        <i class="layui-icon layui-icon-add-1"></i>
	        新增
	    </button>
	</script>

    <!-- 表格操作列（编辑/删除/测试发送按钮） -->
    <script type="text/html" id="base-bar">
		<button class="pear-btn pear-btn-success pear-btn-sm" lay-event="test_send">
			<i class="layui-icon layui-icon-send"></i>测试发送
		</button>
		<button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="edit">
			<i class="layui-icon layui-icon-edit"></i>编辑
		</button>
		<button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="remove">
			<i class="layui-icon layui-icon-delete"></i>删除
		</button>
	</script>

    <!-- 配置状态格式化 -->
	<script type="text/html" id="base-isActive">
		{{#if (d.is_active == 1) { }}
			<i class="layui-icon layui-icon-face-smile" style="font-size: 20px; color: #1E9FFF;"><span>开启</span></i>  
		{{# }else if(d.is_active == 0){ }}
			<i class="layui-icon layui-icon-face-cry" style="font-size: 20px; color: #ff1e1e;"><span>关闭</span></i> 
		{{# } }}
	</script>

    <!-- 引入依赖JS -->
    <script src="../../component/com/api.js"></script>
    <script src="../../component/com/auth.js"></script>
    <script src="../../component/layui/layui.js"></script>
    <script src="../../component/pear/pear.js"></script>
    <script>
        layui.use(['table', 'form', 'jquery', 'common'], function () {
            let table = layui.table;
            let form = layui.form;
            let $ = layui.jquery;
            let common = layui.common;
            // 模块路径（对应新增/编辑页面的路径）
            let MODULE_PATH = "config";
            // 后端接口基础地址 + Token（复用权限逻辑）
            let API_BASE_URL = apiConfig.baseUrl;
            let token = window.localStorage.getItem("token") || window.sessionStorage.getItem("token")

            // 1. 表格列定义（匹配DingTalkConfig模型字段）
            const cols = [
                [{
                    type: 'checkbox'
                },
                {
                    title: '序号',
                    field: 'id',
                    align: 'left',
                    width: 60,
                },
                {
                    title: '配置名称',
                    field: 'name',
                    align: 'left',
                    width: 150,
                },
                {
                    title: '状态',
                    field: 'is_active',
                    align: 'center',
                    width: 80,
                    templet: '#base-isActive'
                },
                {
                    title: '机器人Token',
                    field: 'access_token',
                    align: 'left',
                    width: 300,
                    templet: function (d) {
                        // Token脱敏显示（只展示前10位+后6位）
                        return d.access_token ?
                            `<div style="word-break: break-all;">${d.access_token.substring(0, 10)}****${d.access_token.substring(-6)}</div>` :
                            '<span class="layui-badge layui-badge-danger">未配置</span>';
                    }
                },
                {
                    title: '加签密钥',
                    field: 'secret',
                    align: 'left',
                    width: 200,
                    templet: function (d) {
                        return d.secret ?
                            `<div style="word-break: break-all;">${d.secret.substring(0, 6)}****${d.secret.substring(-4)}</div>` :
                            '<span class="layui-badge layui-badge-gray">未配置</span>';
                    }
                },
                {
                    title: '排序号',
                    field: 'sort_num',
                    align: 'center',
                    width: 80,
                },
                {
                    title: '描述说明',
                    field: 'description',
                    align: 'left',
                    width: 200,
                },
                {
                    title: '创建时间',
                    field: 'create_time',
                    align: 'center',
                    width: 180,
                },
                {
                    title: '更新时间',
                    field: 'update_time',
                    align: 'center',
                    width: 180,
                    hide: true
                },
                {
                    title: '操作',
                    toolbar: '#base-bar',
                    align: 'center',
                    width: 250,
                    fixed: "right"
                }
                ]
            ];

            // 2. 渲染表格（与短信模板逻辑一致）
            table.render({
                elem: '#base-table',
                // 钉钉配置后端接口地址（对应之前定义的URL）
                url: `${API_BASE_URL}/dingding/dingtalk/`,
                page: true,
                // 分页参数配置（与后端保持一致）
                request: {
                    pageName: 'page',
                    limitName: 'limit'
                },
                // 分页条数选择器
                limits: [10, 20, 30, 40, 50, 100],
                limit: 10,
                cols: cols,
                skin: 'line',
                toolbar: '#base-toolbar',
                // 请求头携带Token（权限验证）
                headers: {
                    "Authorization": token
                },
                // 解析后端返回数据（与短信模板接口格式一致）
                parseData: function (res) {
                    return {
                        "code": res.success ? 0 : 1,
                        "msg": res.message || "操作成功",
                        "count": res.data.count,
                        "data": res.data.results,
                        "curr": res.data.current_page
                    };
                },
                // 默认工具栏（刷新、导出等）
                defaultToolbar: [{
                    title: '刷新',
                    layEvent: 'refresh',
                    icon: 'layui-icon-refresh',
                }, 'filter', 'print', 'exports'],
                done: function () {
                    // layer.msg('钉钉配置列表加载完成', { icon: 1, time: 1000, shade: 0.1 });
                }
            });

            // 3. 表格行操作事件（测试发送/编辑/删除）
            table.on('tool(base-table)', function (obj) {
                switch (obj.event) {
                    case "test_send":
                        window.testSend(obj)
                        break;
                    case "edit":
                        window.edit(obj)
                        break;
                    case "remove":
                        window.remove(obj)
                        break;
                }
            });

            // 4. 表格工具栏事件（新增/刷新）
            table.on('toolbar(base-table)', function (obj) {
                switch (obj.event) {
                    case "add_dingtalk":
                        window.addDingtalk(obj)
                        break;
                    case "refresh":
                        window.refresh(obj)
                        break;
                }
            });

            // 5. 筛选表单提交事件（携带筛选参数刷新表格）
            form.on('submit(base-query)', function (data) {
                table.reload('base-table', {
                    where: data.field // 筛选参数：name/is_delete/pt_flag等
                })
                return false;
            });

            // 6. 新增钉钉配置：打开新增弹窗
            window.addDingtalk = function () {
                layer.open({
                    type: 2,
                    title: '新增钉钉机器人配置',
                    shade: 0.1,
                    // 适配移动端和PC端
                    area: ['60%', '90%'],
                    content: `${MODULE_PATH}/dingtalk-config-add.html`
                });
            }

            // 7. 测试发送钉钉消息：打开测试弹窗
            window.testSend = function (obj) {
                // 仅允许有效配置测试发送
                if (obj.data.is_delete === 1) {
                    return layer.msg('已删除的配置无法测试发送', { icon: 2, time: 1500 });
                }
                if (!obj.data.access_token) {
                    return layer.msg('机器人Token未配置，无法测试发送', { icon: 2, time: 1500 });
                }

                layer.open({
                    type: 2,
                    title: `测试发送钉钉消息 - ${obj.data.name}`,
                    shade: 0.1,
                    area: ['600px', '500px'],
                    content: `${MODULE_PATH}/dingtalk-test-send.html?id=${obj.data.id}`
                });
            };

            // 8. 编辑钉钉配置：携带ID打开编辑弹窗
            window.edit = function (obj) {
                layer.open({
                    type: 2,
                    title: `编辑钉钉配置: [${obj.data.name}]`,
                    shade: 0.1,
                    area: ['600px', '500px'],
                    content: `${MODULE_PATH}/dingtalk-config-edit.html?id=${obj.data.id}`
                });
            }

            // 9. 删除钉钉配置：调用后端逻辑删除接口
            window.remove = function (obj) {
                layer.confirm(`确定要${obj.data.is_delete === 0 ? '删除' : '恢复'}配置：[ ${obj.data.name} ] ？`, {
                    icon: 3,
                    title: `提示: ${obj.data.is_delete === 0 ? '配置删除' : '配置恢复'}`
                }, function (index) {
                    layer.close(index);
                    let loading = layer.load();
                    $.ajax({
                        url: `${API_BASE_URL}/dingding/dingtalk/${obj.data.id}/`,
                        dataType: 'json',
                        type: 'delete',
                        headers: {
                            "Authorization": token
                        },
                        success: function (result) {
                            layer.close(loading);
                            if (result.success) {
                                layer.msg(result.message, {
                                    icon: 1,
                                    time: 1000
                                }, function () {
                                    table.reload('base-table'); // 刷新表格
                                });
                            } else {
                                layer.msg(result.message, {
                                    icon: 2,
                                    time: 1000
                                });
                            }
                        },
                        error: function () {
                            layer.close(loading);
                            layer.msg('请求失败，请检查网络', { icon: 2, time: 1500 });
                        }
                    })
                });
            }

            // 10. 刷新表格
            window.refresh = function () {
                table.reload('base-table');
                layer.msg('列表已刷新', { icon: 1, time: 800 });
            }
        })
    </script>
</body>

</html>